package com.zeng.generate.code.other;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import lombok.Data;
import lombok.ToString;

import java.nio.charset.Charset;

@Data
@ToString
public class DialogueInfo {

    private int startText;
    private String tid;
    private String tnr;
    private String laneId;
    private String lpn;
    private String vid;
    private String cmd;
    private String epan;
    private String barrierStatus;
    private String ticketType;
    private String sysDate;
    private String sysTime;
    private int correctMode;
    private String reserved;
    private String blockCheck;
    private int endText;

    private ByteBuf readBuf;
    private ByteBuf writeBuf;
    private int length;

    public DialogueInfo(byte[] bytes) {
        readBuf = Unpooled.buffer(bytes.length);
        readBuf.writeBytes(bytes);

        this.startText = readBuf.getByte(0);
        this.tid = getCharSequence(1, 1);
        this.tnr = getCharSequence(2, 2);
        this.laneId = getCharSequence(4, 2);
        this.lpn = getCharSequence(6, 24);
        this.vid = getCharSequence(30, 8);
        this.cmd = getCharSequence(38, 4);
        this.epan = getCharSequence(42, 32);
        this.barrierStatus = getCharSequence(74, 4);
        this.ticketType = getCharSequence(78, 4);
        this.sysDate = getCharSequence(82, 8);
        this.sysTime = getCharSequence(90, 6);
        this.correctMode = readBuf.getByte(96);
        this.reserved = getCharSequence(97, 30);
        this.blockCheck = getCharSequence(127, 3);
        this.endText =  readBuf.getByte(130);
        this.length = readBuf.readableBytes();
    }

    public byte[] toByteArray() {
        writeBuf = Unpooled.buffer(0,1024);
        writeBuf.writeByte(getStartText());
        writeCharSequence(getTid());
        writeCharSequence(getTnr());
        writeCharSequence(getLaneId());
        writeCharSequence(getLpn());
        writeCharSequence(getVid());
        writeCharSequence(getCmd());
        writeCharSequence(getEpan());
        writeCharSequence(getBarrierStatus());
        writeCharSequence(getTicketType());
        writeCharSequence(getSysDate());
        writeCharSequence(getSysTime());
        writeBuf.writeByte(getCorrectMode());
        writeCharSequence(getReserved());
        writeCharSequence(getBlockCheck());
        writeBuf.writeByte(getEndText());

        int length = writeBuf.readableBytes();
        byte[] array = new byte[length]; // 分配一个新的数组来保存具有该长度的字节数据
        writeBuf.getBytes(writeBuf.readerIndex(), array); // 将字节复制到该数组
        return array;
    }

    private String getCharSequence(int start, int end){
        return readBuf.getCharSequence(start, end, CharsetUtil.UTF_8).toString();
    }

    private void writeCharSequence(CharSequence val){
        writeBuf.writeCharSequence(val, CharsetUtil.UTF_8);
    }
}
